package com.itheima.mm.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.mm.dto.UserLoginDTO;
import com.itheima.mm.entity.PageResult;
import com.itheima.mm.entity.QueryPageBean;
import com.itheima.mm.entity.UserPageQueryParams;
import com.itheima.mm.exception.BaseException;
import com.itheima.mm.mapper.UserMapper;
import com.itheima.mm.pojo.User;
import com.itheima.mm.service.UserService;
import com.itheima.mm.utils.DateUtils;
import com.itheima.mm.vo.CourseVO;
import com.itheima.mm.vo.UserLoginVO;
import org.apache.commons.codec.cli.Digest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.Date;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    UserMapper userMapper;

    //@Value("${mm.md5.salt}")
    @Value("${mm.md5.salt}")
    private String salt;

    @Override
    public User login(UserLoginDTO userLoginDTO) {


        User user = userMapper.getByUsername(userLoginDTO.getUsername());

        if(user==null){
            throw new BaseException("用户名错误");
        }

        byte[] bytes = (userLoginDTO.getPassword()+salt).getBytes();
        String md5 = DigestUtils.md5DigestAsHex(bytes);
        if(!md5.equals(user.getPassword())){
            System.out.println(md5);
            throw new BaseException("密码错误");
        }


        if(user.getState()==1){
            throw new BaseException("用户已被禁用无法登录，请联系管理员");

        }

        return user;
    }

    @Override
    public PageResult findListByPage(QueryPageBean<UserPageQueryParams>
                                                 queryPageBean) {
        
        PageHelper.startPage(queryPageBean.getCurrentPage(),
                queryPageBean.getPageSize());

        //调用mapper查询数据
        Page<User> page = (Page<User>) userMapper.findByCondition(queryPageBean.getQueryParams());

        //返回数据
        return new PageResult(page.getTotal(),page.getResult());
    }
    @Override
    public void add(User user) {
        user.setCreateDate(DateUtils.parseDate2String(new Date()));
        userMapper.insert(user);
    }
    @Override
    public User findById(Integer id) {
        return userMapper.findById(id);
    }
    @Override
    public void update(User user) {
        userMapper.update(user);
    }
    @Override
    public void deleteUser(Integer id) {

        userMapper.deleteUser(id);
    }

}
